home *** CD-ROM | disk | FTP | other *** search
- /* SortWindow.cpp
- Charles Higgins
- */
-
- #include "SortWindow.h"
-
- void swap(BWindow *aWindow, char **s1, char **s2);
- char **addlist( BWindow *aWindow, char **list, int numberOfThings);
-
- SortWindow::SortWindow(BRect frame)
- : BWindow(frame, "Sort", B_TITLED_WINDOW, 0)
- {
- BRect aRect = frame;
- BListView *aView;
-
- aRect.OffsetTo(B_ORIGIN);
- aView = new BListView(aRect, "SortView", B_FOLLOW_ALL, B_WILL_DRAW);
- this->AddChild(aView);
- }
-
- void swap(BWindow *aWindow, char **s1, char **s2)
- {
- BView *aView;
- char *temp;
-
- aView = aWindow->FindView("SortView");
- aWindow->Lock();
- temp = *s1;
- *s1 = *s2;
- *s2 = temp;
- aView->Invalidate();
- aWindow->Unlock();
- }
-
- char **addlist( BWindow *aWindow, char **list, int numberOfThings)
- {
- BListView *aView;
- int i;
-
- aView = (BListView*)aWindow->FindView("SortView");
- aWindow->Lock();
- for(i=0;i< numberOfThings;i++)
- aView->AddItem(list[i]);
- aWindow->Unlock();
- return((char**)aView->Items());
- }
-
- void SortWindow::DoSort
- ( char *thingsToSort[], int numberOfThings, SortType sortMethod)
- {
- short i,
- j,
- k,
- sorted = FALSE;
- char **myList;
-
- myList = addlist( this, thingsToSort, numberOfThings);
- switch(sortMethod)
- {
- case kBubbleSort:
- i = numberOfThings-1;
- while(i>0)
- {
- j=i;
- for(k=0;k<i;++k)
- {
- if (0 < strcmp(myList[k],myList[j]))
- j = k;
- }
- swap( this, &myList[i], &myList[j]);
- i--;
- }
- break;
- case kExchange:
- while(!sorted)
- {
- sorted = TRUE;
- for(i=0;i<numberOfThings-1;i++)
- {
- if(0 < strcmp(myList[i],myList[i+1]))
- {
- sorted = FALSE;
- swap( this, &myList[i], &myList[i+1]);
- }
- }
- }
- break;
- case kMySort:
- QuickSort( myList, 0, numberOfThings);
- break;
- }
- memcpy(thingsToSort,myList,numberOfThings*sizeof(char*));
- be_app->PostMessage(B_QUIT_REQUESTED);
- }
-
- void SortWindow::QuickSort( char **list, int first, int last)
- {
- int j,i;
-
- while(last - first > 1)
- {
- i = first;
- j = last;
- for(;;)
- {
- while(++i < last && strcmp(list[i],list[first]) < 0)
- ;
- while(--j > first && strcmp(list[j],list[first]) > 0)
- ;
- if (i >= j)
- break;
- swap( this, &list[i], &list[j]);
- }
- if( j == first)
- {
- ++first;
- continue;
- }
- swap( this, &list[first], &list[j]);
- if(j - first < last - (j+1))
- {
- QuickSort( list,first,j);
- first = j + 1;
- }
- else
- {
- QuickSort( list,j+1,last);
- last = j;
- }
- }
- }
-